package com.insist.service.impl;

import com.insist.dao.CartInfoDao;
import com.insist.entity.CartInfo;
import com.insist.entity.ProductInfo;
import com.insist.model.CartProductModel;
import com.insist.service.CartService;
import com.insist.service.ProductService;
import com.insist.util.BeanCopierUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/11/6.
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    CartInfoDao cartInfoDao;

    @Autowired
    ProductService productService;

    @Override
    public void addCart(Long productId, Long userId, Integer number) {
        CartInfo cartInfo =cartInfoDao.getByProductIdAndUserId(productId, userId);
        if(cartInfo == null){
            cartInfo = new CartInfo();
            cartInfo.setProductId(productId);
            cartInfo.setUserId(userId);
            cartInfo.setNum(number);
        }else {
            cartInfo.setNum(number + cartInfo.getNum());
        }
        cartInfoDao.save(cartInfo);
    }

    @Override
    public List<CartProductModel> getCart(Long userId){
        List<CartProductModel> rsList = new ArrayList<>();
        List<CartInfo> cartInfos = cartInfoDao.findByUserId(userId);
        for(CartInfo cartInfo:cartInfos){
            ProductInfo info = productService.getProductById(cartInfo.getProductId());
            CartProductModel cartProductModel = new CartProductModel();
            BeanCopierUtils.copyProperties(info, cartProductModel);
            cartProductModel.setProductNumber(cartInfo.getNum());
            cartProductModel.setProductPrice(info.getMoney());
            rsList.add(cartProductModel);
        }
        return rsList;
    }

    @Override
    public CartProductModel getCart(Long id, Long productId) {
        CartInfo cartInfo = cartInfoDao.getByProductIdAndUserId(productId,id);
        ProductInfo info = productService.getProductById(cartInfo.getProductId());
        CartProductModel cartProductModel = new CartProductModel();
        BeanCopierUtils.copyProperties(info, cartProductModel);
        cartProductModel.setProductNumber(cartInfo.getNum());
        cartProductModel.setProductPrice(info.getMoney());
        return cartProductModel;
    }

    @Override
    public void delCart(Long productId, Long userId) {
        CartInfo cartInfo=cartInfoDao.getByProductIdAndUserId(productId, userId);
        if(cartInfo!=null){
            cartInfoDao.delete(cartInfo);
        }
    }

    @Override
    public void editCart(Long productId, Integer num, Long userId) {
        CartInfo cartInfo=cartInfoDao.getByProductIdAndUserId(productId, userId);
        if(cartInfo!=null){
            cartInfo.setNum(num);
            cartInfoDao.save(cartInfo);
        }

    }
}
